/** 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.free.i.naming;


import java.util.Enumeration;
import java.util.Properties;

import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;

/**
 * Load a properties file from a physical file
 * @author  stefano
 */
public class JndiPropertiesLoader {

    /**
     * Singleton
     */
    private JndiPropertiesLoader() {
        super();
    }
 
    /**
     * Read configurations param name/value pairs in a properties object
     * @param lookupName is the name too look for to find the past and load properties from a JNDI (like the LDAP) service provider
     * @return a properties object loaded, or null if something goes wrong
     * @throws NamingException 
     */
    public static final Properties lookupProperties(String lookupName) throws NamingException  {
        
        //Then loading config from the naming provider
        Object storedConfig = CachedNamingProviderProxy.getInstance().lookup(lookupName);
        Properties configuration = null;
        
        try{        
            Reference namingReference = (Reference) storedConfig;
            Enumeration<RefAddr> names = namingReference.getAll();

            configuration = new Properties();
      
            String tmpAttribName = null;
            String tmpAttribValue = null;
      
            RefAddr refAddr = null;
            //Fetching entries found
            while(names.hasMoreElements()){
                  refAddr = names.nextElement();
                  tmpAttribName = refAddr.getType();
                  tmpAttribValue = ((String)refAddr.getContent());
                  configuration.put(tmpAttribName,tmpAttribValue);
            }
        }catch(ClassCastException ccExc){
               throw (new NamingException("Object found is not a configuration to store as properties:" + ccExc.getMessage()));
        }
                
        return configuration;
    }

}
